import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:robot3/services.dart';
import 'package:robot3/xiangqing.dart';

import 'backButton1.dart';

// https://docs.flutter.dev/get-started/fundamentals/networking#introduction-to-retrieving-data-over-the-network
// https://docs.flutter.dev/cookbook/networking/fetch-data
// https://api.flutter.dev/flutter/painting/BoxDecoration-class.html
// flutter create --sample=material.Card.1 mysample

class MyButton01 extends StatefulWidget {
  final double alpha;
  final Color containerColor;
  final ShapeBorder shape;
  final BorderSide? border;
  final Color textColor;
  final Size size;
  final double fontSize;
  final FontWeight fontWeight;
  final String fontFamily;
  final String text;
  final void Function(String) onClick;

  const MyButton01({
    super.key,
    this.alpha = 1.0,
    this.containerColor = const Color(0xFF000000),
    this.shape = const RoundedRectangleBorder(
      borderRadius: BorderRadius.all(Radius.circular(16)),
    ),
    this.border,
    this.textColor = Colors.white,
    this.size = const Size(144, 44),
    this.fontSize = 14.0,
    this.fontWeight = FontWeight.normal,
    this.fontFamily = 'Roboto',
    required this.text,
    required this.onClick,
  });

  @override
  _MyButton01State createState() => _MyButton01State();
}

class _MyButton01State extends State<MyButton01> {
  bool _isPressed = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) {
        setState(() {
          _isPressed = true;
        });
      },
      onTapUp: (_) {
        setState(() {
          _isPressed = false;
        });
        widget.onClick(widget.text);
      },
      onTapCancel: () {
        setState(() {
          _isPressed = false;
        });
      },
      child: Opacity(
        opacity: _isPressed ? widget.alpha * 0.5 : widget.alpha, // 点击时降低透明度
        child: Container(
          width: widget.size.width,
          height: widget.size.height,
          decoration: ShapeDecoration(
            color: widget.containerColor,
            shape: widget.shape,
            shadows:
                _isPressed
                    ? [
                      BoxShadow(color: Colors.black26, blurRadius: 5),
                    ] // 点击时增加阴影效果
                    : [],
          ),
          child: Center(
            child: Text(
              widget.text,
              style: TextStyle(
                fontSize: widget.fontSize,
                fontWeight: widget.fontWeight,
                color: widget.textColor,
                fontFamily: widget.fontFamily,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class RobotList extends StatelessWidget {
  final double height; // 新增参数
  RobotList({super.key, this.height = 400});

  final List<String> entries = List.generate(1000, (index) => 'Item $index');
  final List<int> colorCodes = <int>[600, 500, 100];

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: height, // 指定 ListView 的高度
      child: ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          print("${index}");
          return Container(
            height: 50,
            color: Colors.amber[colorCodes[index % 3]],
            child: Center(child: Text('Entry ${entries[index]}')),
          );
        },
      ),
    );
  }
}

class RobotList1 extends StatelessWidget {
  final double height; // 新增参数
  RobotList1({super.key, this.height = 400});

  final List<String> entries = List.generate(4, (index) => 'Item $index');
  final List<int> colorCodes = <int>[600, 500, 100];

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 120,
      height: 540, // 指定 ListView 的高度
      child: ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          print("${index}");
          return Container(
            height: 50,
            width: 50,
            color: Colors.amber[colorCodes[index % 3]],
            child: Center(child: Text('Entry ${entries[index]}')),
          );
        },
      ),
    );
  }
}

// List<Color> colors = [Colors.red,
//   Colors.red, Colors.red,
//   Colors.red, Colors.red,
//   Colors.red, Colors.red,
//   Colors.red
// ];

List<Color> colors = [
  Color(0xFFE57373), // 浅红
  Color(0xFFF06292), // 粉红
  Color(0xFFBA68C8), // 紫色
  Color(0xFF64B5F6), // 浅蓝
  Color(0xFF4FC3F7), // 天蓝
  Color(0xFF81C784), // 浅绿
  Color(0xFFFFD54F), // 黄色
  Color(0xFFFFB74D), // 橙色
  Color(0xFFA1887F), // 棕色
  Color(0xFF90A4AE), // 灰色
];

class RobotListWidget extends StatelessWidget {
  final double ratio;

  const RobotListWidget({super.key, required this.ratio});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(0.0),
      // 添加内边距
      color: Colors.black,
      width: 120 / ratio,
      // 固定宽度
      height: 540 / ratio,
      // 固定高度
      child: ListView.separated(
        padding: EdgeInsets.zero,
        // 确保列表没有额外内边距
        shrinkWrap: true,
        // 避免默认的滚动行为影响布局
        itemCount: colors.length,
        // itemCount:4,
        separatorBuilder: (context, index) => SizedBox(height: 20 / ratio),
        itemBuilder: (context, index) {
          return Container(
            width: 120 / ratio,
            height: 120 / ratio,
            color: colors[index],
          );
        },
      ),
    );
  }
}

class RobotText extends StatelessWidget {
  final String text; // 新增参数

  const RobotText({super.key, required this.text});

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: const TextStyle(
        fontSize: 48 / ratio,
        // 设置字体大小
        color: Colors.blue,
        // 设置字体颜色
        fontWeight: FontWeight.bold,
        // 设置字体粗细
        // fontStyle: FontStyle.italic, // 设置字体样式为斜体
        letterSpacing: 2.0,
        // 设置字母间距
        wordSpacing: 15.0, // 设置单词间距
        // decoration: TextDecoration.underline, // 设置文本下划线
        // decorationColor: Colors.red, // 设置下划线的颜色
        // decorationThickness: 2.0, // 设置下划线的粗细
      ),
    );
  }
}

extension TextStyling on Widget {
  Widget withBackgroundAndPadding() {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0x0F000000), // 替代 `MYBLACK_Percent5`
        borderRadius: BorderRadius.circular(
          6 / ratio,
        ), // 替代 `RoundedCornerShape(6.px)`
      ),
      padding: const EdgeInsets.symmetric(
        horizontal: 20 / ratio, // 替代 `17.px`
        vertical: 5 / ratio, // 替代 `10.px`
      ),
      child: this,
    );
  }
}

class TitleText30 extends StatelessWidget {
  final String text; // 新增参数
  const TitleText30({super.key, required this.text});

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      maxLines: 300,
      overflow: TextOverflow.ellipsis,
      style: const TextStyle(
        fontSize: 30 / ratio,
        // 设置字体大小
        color: MyBlack,
        // 设置字体颜色
        fontWeight: FontWeight.normal,
        // 设置字体粗细
        // fontStyle: FontStyle.italic, // 设置字体样式为斜体
        letterSpacing: 0.0,
        // 设置字母间距
        wordSpacing: 0.0, // 设置单词间距
        // decoration: TextDecoration.underline, // 设置文本下划线
        // decorationColor: Colors.red, // 设置下划线的颜色
        // decorationThickness: 2.0, // 设置下划线的粗细
      ),
    );
  }
}

class TitleText extends StatelessWidget {
  final String text; // 新增参数

  TitleText({super.key, required this.text});

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      maxLines: 3,
      overflow: TextOverflow.ellipsis,
      style: const TextStyle(
        fontSize: 30 / ratio,
        // 设置字体大小
        color: MyBlack,
        // 设置字体颜色
        fontWeight: FontWeight.bold,
        // 设置字体粗细
        // fontStyle: FontStyle.italic, // 设置字体样式为斜体
        letterSpacing: 0.0,
        // 设置字母间距
        wordSpacing: 0.0, // 设置单词间距
        // decoration: TextDecoration.underline, // 设置文本下划线
        // decorationColor: Colors.red, // 设置下划线的颜色
        // decorationThickness: 2.0, // 设置下划线的粗细
      ),
    );
  }
}

const MyBlack = Color(0xff333333);
const MyBLUE = Color(0xff2c72e5);

/// 全局方法，用于显示 SnackBar 消息
void showMessage({required BuildContext context, required String text}) {
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(text), // 显示传入的文本
      duration: const Duration(seconds: 2), // 持续时间为 2 秒
    ),
  );
}

class RobotButton extends StatelessWidget {
  final void Function(String) onClick;

  const RobotButton({super.key, required this.onClick});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.red[100],
        elevation: 0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8), // 圆角边框
        ),
      ),
      onPressed: () {
        this.onClick('RobotButton');
        print("ElevatedButton onPressed");
      },
      child: Text("RobotButton"),
    );
  }
}

//   这个card会尽可能的大.
class RobotCard extends StatelessWidget {
  // 在构造函数中添加 child 参数，类型为 Widget
  final Widget child;
  final Color color;

  const RobotCard({
    super.key,
    required this.child,
    this.color = Colors.white38,
  }); // Default value for color

  @override
  Widget build(BuildContext context) {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxWidth: double.infinity, // 固定宽度
        maxHeight: double.infinity, // 最小高度设为 0，允许自动适应子组件
      ),
      // width: 300, // 设置宽度
      // height: 300, // 设置高度
      child: Card(
        margin: EdgeInsets.zero,
        // Remove default margins for full screen
        shadowColor: Colors.transparent,
        // 设置阴影颜色
        color: color,
        // 设置卡片的背景色
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20 / ratio), // 设置圆角
        ),
        child: Padding(
          padding: const EdgeInsets.all(
            0.0 / ratio, // 像素值直接使用 dp 转换
          ),
          child: Center(child: child),
        ),
      ),
    );
  }
}

class RobotFixedSizeCard extends StatelessWidget {
  // 在构造函数中添加 child 参数，类型为 Widget
  final Widget child;
  final double width;
  final double height;

  const RobotFixedSizeCard({
    super.key,
    required this.child,
    required this.width,
    required this.height,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: width, // 设置宽度
      height: height, // 设置高度
      child: Card(
        color: Colors.white, // 设置卡片的背景色
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(40 / 2.5), // 设置圆角
        ),
        child: Padding(
          padding: const EdgeInsets.all(
            16.0 / ratio, // 像素值直接使用 dp 转换
          ),
          child: Center(child: child),
        ),
      ),
    );
  }
}

class RobotSearchEdit extends StatelessWidget {
  // 添加 TextEditingController 用于获取输入内容
  final TextEditingController _controller = TextEditingController();

  // 在构造函数中添加 child 参数，类型为 Widget
  // final Widget child;
  // final double width;
  // final double height;

  RobotSearchEdit({super.key});

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller, // 绑定 controller
      decoration: InputDecoration(
        // contentPadding:EdgeInsets.all(0),
        // contentPadding: EdgeInsets.symmetric(vertical: 4, horizontal: 12), // 设置顶部和底部的内边距为 0
        hintText: '请输入关键词搜索',
        hintStyle: TextStyle(
          color: Colors.grey, // 设置 hint 文字颜色为灰色
          fontSize: 14, // 设置 hint 文字大小
        ),
        // labelText: 'Email',
        suffixIcon: Padding(
          padding: EdgeInsets.only(right: 4),
          child: InkWell(
            onTap: () {
              showMessage(context: context, text: _controller.text);
              // 点击时打印输入内容
              print("Search icon clicked! 用户输入内容：${_controller.text}");
              // 这里写你点击后要执行的操作
            },
            borderRadius: BorderRadius.circular(8.0), // 设置圆角
            child: Container(
              padding: EdgeInsets.all(8.0), // 添加内边距
              decoration: BoxDecoration(
                color: Colors.blue.withAlpha(100), // 设置背景色为蓝色
                borderRadius: BorderRadius.circular(8.0), // 圆角效果
              ),
              child: Icon(Icons.search, color: Colors.white), // 设置图标颜色为白色
            ),
          ),
        ),
        // border: const OutlineInputBorder(),
        focusedBorder: const OutlineInputBorder(
          borderSide: BorderSide(color: Colors.blue, width: 1.0), // 聚焦时边框为蓝色
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(color: Colors.blue, width: 1.0), // 启用时边框为蓝色
        ),
      ),
    );
  }
}

class RobotEditText extends StatelessWidget {
  final TextEditingController controller;
  final ValueChanged<String> onTextChanged; // Callback for text change
  final TextInputType keyboardType;
  final bool enabled;
  final bool showSuffixIcon;  // New parameter to decide whether to show suffix icon

  const RobotEditText({
    super.key,
    required this.onTextChanged,
    required this.controller,
    this.enabled = true,
    this.keyboardType = TextInputType.text,
    this.showSuffixIcon = false,  // Default is false, no suffix icon
  });

  @override
  Widget build(BuildContext context) {
    return TextField(
      onTap: () {
        print("onTap");
      },
      enabled: enabled,
      keyboardType: keyboardType,
      // Restrict to numeric keyboard
      cursorWidth: 5 / ratio,
      style: TextStyle(
        height: 1,
        color: Colors.black, // 设置 hint 文字颜色为灰色
        fontSize: 24 / ratio, // 设置 hint 文字大小
      ),

      controller: controller,
      // 绑定 controller
      onChanged: onTextChanged,
      // Notify when text changes
      decoration: InputDecoration(
        suffixIcon:showSuffixIcon?
        Icon(
          Icons.keyboard_arrow_down_sharp,
          color: Colors.grey,
          size: 36.0/ratio, // Set the icon size here
        ):null,
        focusedBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),

        disabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),

        border: OutlineInputBorder(
          borderSide: const BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ),
          borderRadius: const BorderRadius.all(Radius.circular(10 / ratio)),
        ),
        // Optional: Add a border for clarity
        filled: true,
        fillColor: MyBlack.withOpacity(0.05),
        contentPadding: EdgeInsets.symmetric(
          horizontal: 20 / ratio,
          vertical: 0.0,
        ),
        // Adjust padding
        // contentPadding: EdgeInsets.symmetric(vertical: 4, horizontal: 12), // 设置顶部和底部的内边距为 0
        hintText: '请输入',
        hintStyle: TextStyle(
          color: Colors.grey, // 设置 hint 文字颜色为灰色
          fontSize: 24 / ratio, // 设置 hint 文字大小
        ),
      ),
    );
  }
}

///末尾显示输入字数
class CharacterCountInput extends StatefulWidget {
   final String init;
   final ValueChanged<String> onTextChanged; // Callback for text change

  const CharacterCountInput({super.key, required this.init, required this.onTextChanged});
  @override
  State<StatefulWidget> createState() {
  return  _CharacterCountInputState(init: init, onTextChanged: onTextChanged,);
  }
}


class _CharacterCountInputState extends State<CharacterCountInput> {
  final ValueChanged<String> onTextChanged; // Callback for text change
  final String init;
  final TextInputType keyboardType;
  final TextEditingController _controller;
  final int maxCharacters = 20;

  int  length = 0 ;

  _CharacterCountInputState({
  this.keyboardType = TextInputType.text, // Default value set here
    required this.init,
    required this.onTextChanged,
  }): _controller= TextEditingController(text:init);

  @override
  void initState() {
    print("_CharacterCountInputState initState");
    super.initState();
    length= _controller.text.length;
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
  print("_CharacterCountInputState build");
    return TextField(
      maxLength: maxCharacters,
      controller:_controller,
      onTap: () {
        print("onTap");
      },
      enabled: true,
      keyboardType: keyboardType,
      cursorWidth: 5 / ratio,
      style: TextStyle(
        height: 1,
        color: Colors.black, // 设置 hint 文字颜色为灰色
        fontSize: 24 / ratio, // 设置 hint 文字大小
      ),

      onChanged: (text){
        setState(() {
          length = text.length;
        });
        onTextChanged(text);
        },
        // Notify when text changes
        decoration: InputDecoration(
          counterText:"",
        suffixIcon:
        Row(
        mainAxisSize:MainAxisSize.min,
        mainAxisAlignment:MainAxisAlignment.end,
        children: [
        Padding(
        padding: const EdgeInsets.only(right: 13/ratio), // Adjust padding
        child: Text(
        '${length}/${maxCharacters}',
        style: TextStyle(fontSize: 24/ratio, color: MyBLUE,fontWeight: FontWeight.w500),
        ),
        ),]),

        focusedBorder: const OutlineInputBorder(
        borderSide: BorderSide(
        color: Colors.transparent,
        width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),

        disabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),

        border: OutlineInputBorder(
          borderSide: const BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ),
          borderRadius: const BorderRadius.all(Radius.circular(10 / ratio)),
        ),
        // Optional: Add a border for clarity
        filled: true,
        fillColor: MyBlack.withOpacity(0.05),
        contentPadding: EdgeInsets.symmetric(
          horizontal: 20 / ratio,
          vertical: 0.0,
        ),
        // Adjust padding
        // contentPadding: EdgeInsets.symmetric(vertical: 4, horizontal: 12), // 设置顶部和底部的内边距为 0
        hintText: '请输入',
        hintStyle: TextStyle(
          color: Colors.grey, // 设置 hint 文字颜色为灰色
          fontSize: 24 / ratio, // 设置 hint 文字大小
        ),
      ),
    );
  }
}

///只删除了controller
class RobotEditText2 extends StatelessWidget {
  final ValueChanged<String> onTextChanged; // Callback for text change
  final TextInputType keyboardType;
  final bool enabled;
  final String init;

  const RobotEditText2({
    super.key,
    required this.onTextChanged,
    required this.init,
    this.enabled = true,
    this.keyboardType = TextInputType.text,
  });

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: TextEditingController(text: init),
      onTap: () {
        print("onTap");
      },
      enabled: enabled,
      keyboardType: keyboardType,
      // Restrict to numeric keyboard
      cursorWidth: 5 / ratio,
      style: TextStyle(
        height: 1,
        color: Colors.black, // 设置 hint 文字颜色为灰色
        fontSize: 24 / ratio, // 设置 hint 文字大小
      ),

      onChanged: onTextChanged,
      // Notify when text changes
      decoration: InputDecoration(
        // suffixIcon: Icon(
        //   Icons.keyboard_arrow_down_sharp,
        //   color: Colors.grey,
        //   size: 36.0/ratio, // Set the icon size here
        // ),
        focusedBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),
        enabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),

        disabledBorder: const OutlineInputBorder(
          borderSide: BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ), // 聚焦时边框为蓝色
        ),

        border: OutlineInputBorder(
          borderSide: const BorderSide(
            color: Colors.transparent,
            width: 1.0 / ratio,
          ),
          borderRadius: const BorderRadius.all(Radius.circular(10 / ratio)),
        ),
        // Optional: Add a border for clarity
        filled: true,
        fillColor: MyBlack.withOpacity(0.05),
        contentPadding: EdgeInsets.symmetric(
          horizontal: 20 / ratio,
          vertical: 0.0,
        ),
        // Adjust padding
        // contentPadding: EdgeInsets.symmetric(vertical: 4, horizontal: 12), // 设置顶部和底部的内边距为 0
        hintText: '请输入',
        hintStyle: TextStyle(
          color: Colors.grey, // 设置 hint 文字颜色为灰色
          fontSize: 24 / ratio, // 设置 hint 文字大小
        ),
      ),
    );
  }
}

void showRobotPopup(
  BuildContext context, {
  double x = 400,
  double y = 400,
  required Container child,
}) {
  var screen = MediaQuery.of(context).size.width;
  var screen2 = MediaQuery.of(context).size.height;
  var w = (x / screen) * 2 - 1;
  var h = (y / screen2) * 2 - 1;
  showDialog(
    context: context,
    barrierDismissible: true, // 允许点击外部关闭对话框
    useSafeArea: false,
    builder: (BuildContext context) {
      return Dialog(
        alignment: Alignment(w, h),
        insetPadding: EdgeInsets.zero, // 让对话框填满屏幕
        child: child,
      );
    },
  );
}

/**
 *  类似于 compose的 fillMaxSize
 */
class RobotFillMaxSizeCard extends StatelessWidget {
  final Widget content;

  const RobotFillMaxSizeCard({Key? key, required this.content})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      // 设置容器宽度填满可用空间
      height: double.infinity,
      // 设置容器宽度填满可用空间
      padding: const EdgeInsets.only(left: 30.0, right: 30.0, top: 30),
      // 设置左右边距
      decoration: BoxDecoration(
        color: Colors.red,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(40.0), // 设置左上角圆角
          topRight: Radius.circular(40.0), // 设置右上角圆角
          bottomLeft: Radius.circular(40), // 设置左下角为直角
          bottomRight: Radius.circular(40), // 设置右下角为直角
        ),
      ),
      child: content, // 调用传入的内容
    );
  }
}

//用在系统信息的渲染列表,是否渲染成功.
class RobotOutLineText extends StatelessWidget {
  const RobotOutLineText({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 105,
      height: 36,
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(1.0), // 设置背景色，可选
        border: Border.all(
          color: MyBLUE.withOpacity(0.2), // 设置边框颜色为红色
          width: 2, // 设置边框宽度为 1px
        ),
        borderRadius: BorderRadius.circular(6), // 设置圆角半径
      ),
      child: const Center(
        child: Text(
          '渲染成功',
          style: TextStyle(
            color: MyBLUE, // 文字颜色
            fontSize: 20, // 文字大小
            fontWeight: FontWeight.normal, // 字体加粗
          ),
        ),
      ),
    );
  }
}

class RobotPopupMenuButton extends StatelessWidget {
  final double width;
  final double height;
  final double itemHeight;
  final double offsetY;
  final Map<String, String> map;
  final Function(String selectedItem) onItemSelected;

  final TextEditingController phoneController = TextEditingController();

  RobotPopupMenuButton({
    super.key,
    required this.width,
    required this.itemHeight,
    required this.offsetY,
    required this.onItemSelected,
    required this.map,
    required this.height,
  });

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      constraints: BoxConstraints(minWidth: width, maxWidth: width),
      padding: EdgeInsets.only(left: 0),
      menuPadding: EdgeInsets.zero,
      itemBuilder: (context) => buildItems(),
      offset: Offset(0, offsetY),
      color: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(0),
          bottomRight: Radius.circular(0),
          topRight: Radius.circular(0),
          bottomLeft: Radius.circular(0),
        ),
      ),
      onSelected: (e) {
        print("onSelected:" + e);
        print("onSelected:" + map[e].toString());
        onItemSelected(e);
      },
      onCanceled: () => print('onCanceled'),
      // 移除 PopupMenuButton 的外部 padding
      child: SizedBox(
        width: width,
        height: height,
        child: RobotEditText(
          enabled: false,
          onTextChanged: (text) {},
          controller: phoneController,
        ),
      ),
    );
  }

  List<PopupMenuItem<String>> buildItems() {
    return map.keys
        .toList()
        .map(
          (e) => PopupMenuItem<String>(
            height: 1, // 设置菜单项的高度
            padding: EdgeInsets.zero, // 移除 PopupMenuItem 的内边距
            value: e,
            child: Container(
              color: Colors.transparent,
              height: itemHeight,
              width: width,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 30 / ratio),
              child: Text(
                e,
                style: TextStyle(color: MyBlack, fontSize: 24 / ratio),
              ),
            ),
          ),
        )
        .toList();
  }
}

///和上面的对比只修改了map为list.
class RobotPopupMenuButton2 extends StatelessWidget {
  final double width;
  final double height;
  final double itemHeight;
  final double offsetY;
  final String init;
  final List<String> map;
  final Function(String selectedItem) onItemSelected;

  final TextEditingController phoneController;

  RobotPopupMenuButton2({
    super.key,
    required this.width,
    required this.itemHeight,
    required this.offsetY,
    required this.init,
    required this.onItemSelected,
    required this.map,
    required this.height,
  }) : phoneController = TextEditingController(text: init);

  @override
  Widget build(BuildContext context) {
    return PopupMenuButton<String>(
      // position: PopupMenuPosition.under, // This positions the menu under the button
      constraints: BoxConstraints(minWidth: width, maxWidth: width),
      padding: EdgeInsets.only(left: 0),
      menuPadding: EdgeInsets.zero,
      itemBuilder: (context) => buildItems(),
      offset: Offset(0, offsetY),
      color: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(0),
          bottomRight: Radius.circular(0),
          topRight: Radius.circular(0),
          bottomLeft: Radius.circular(0),
        ),
      ),
      onSelected: (e) {
        print("onSelected:" + e);
        // print("onSelected:"+map[e].toString());
        onItemSelected(e);
      },
      onCanceled: () => print('onCanceled'),
      // 移除 PopupMenuButton 的外部 padding
      child: SizedBox(
        width: width,
        height: height,
        child: RobotEditText(
          showSuffixIcon: true,
          enabled: false,
          onTextChanged: (text) {},
          controller: phoneController,
        ),
      ),
    );
  }

  List<PopupMenuItem<String>> buildItems() {
    return map
        .map(
          (e) => PopupMenuItem<String>(
            height: 1, // 设置菜单项的高度
            padding: EdgeInsets.zero, // 移除 PopupMenuItem 的内边距
            value: e,
            child: Container(
              color: Colors.transparent,
              height: itemHeight,
              width: width,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 30 / ratio),
              child: Text(
                e,
                style: TextStyle(color: MyBlack, fontSize: 24 / ratio),
              ),
            ),
          ),
        )
        .toList();
  }
}

///
/// 实现了以下功能:
///     1: 有背景图片.
///     2 有padding 30.
///     3 左下角有返回button.
///
class RobotScreen extends StatelessWidget {
  final Widget child;

  const RobotScreen({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // Image equivalent to the Image composable
          Image.asset(
            'images/bg.png', // 替换为你的图片路径
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 30 / ratio,
              right: 30 / ratio,
              top: 30 / ratio,
              bottom: 30 / ratio,
            ),
            child: // 加载完成后显示商品信息
                child,
          ),
          Positioned(
            left: 30 / ratio,
            bottom: 30 / ratio,
            child: BackButton1(),
          ),
        ],
      ),
    );
  }
}

class RobotSwitch extends StatelessWidget {
  final bool selected;
  final Function(bool) onToggle;

  const RobotSwitch({
    super.key,
    required this.selected,
    required this.onToggle,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 44,
      height: 20,
      child: FittedBox(
        fit: BoxFit.scaleDown,
        child: Switch(
          padding: EdgeInsets.zero,
          activeColor: Color(0xff165dff),
          thumbColor: WidgetStateProperty.resolveWith<Color>((
            Set<WidgetState> states,
          ) {
            return Colors.white;
          }),
          trackColor: WidgetStateProperty.resolveWith<Color>((
            Set<WidgetState> states,
          ) {
            if (states.contains(WidgetState.selected)) {
              // If the switch is on (selected), set the color to blue
              return Color(0xff165dff);
            }
            // If the switch is off (not selected), set the color to grey
            return Color(0xffd3d3d3);
          }),
          trackOutlineColor: WidgetStateProperty.resolveWith<Color>((
            Set<WidgetState> states,
          ) {
            return Colors.transparent;
          }),
          value: selected,
          onChanged: (bool value) {
            onToggle(value);
            // provider.setOk1(value);
          },
        ),
      ),
    );
  }
}
